package com.cm367.teamc.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;

import com.cm367.teamc.bean.User;
import com.cm367.teamc.dao.UserDAO;

@ManagedBean
@ApplicationScoped
public class UserService {

	@ManagedProperty(value = "#{userDAO}")
	private UserDAO userDAO;

	public User findUser(String userID, String password) throws SQLException {
		return userDAO.findUser(userID, password);
	}

	public String create(String userID, String password, String role,
			String userName, String department) {
		if (!userDAO.validateUserID(userID)) {
			try {
				if (role.equals("User")) {
					if (!userDAO.existRole(department)) {
						return "Manager Not Found";
					}
				} else {
					if (userDAO.existRole(department)) {
						return "Manager Exist";
					}
				}
				if (userDAO.save(userID, password, role, userName, department)) {
					return "createSuccess";
				}
				return "createFail";
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return "exist";
	}

	public boolean delete(String userID) {
		try {
			return userDAO.delete(userID);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public List<User> findAllUser() {
		List<User> users = new ArrayList<User>();
		try {
			return userDAO.findAllUser();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return users;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

}
